import { defineStore } from "pinia";
import { ref } from "vue";
import io, { Socket } from "socket.io-client";
import { useAuthStore } from "./auth";
import emitter from "@/utils/emitter";

export const userSocketStore = defineStore("socket", () => {
  const socket = ref<Socket | null>(null);

  function connect() {
    if (socket.value?.connected) {
      return false;
    }
    const authStore = useAuthStore();
    socket.value = io(`ws://localhost:3001?token=${authStore.token}`);

    socket.value.on("connect", () => {
      console.log("链接成功");
    });
    socket.value.on("disconnect", () => {
      console.log("断开链接");
    });
    socket.value.on("error", data => {
      console.log("error", data.message);
    });
    socket.value.on("chatMessage", data => {
      emitter.emit("chatMessage", data);
    });
  }

  function disconnect() {
    if (socket.value?.connected) {
      socket.value.disconnect();
    }
  }

  function sendMessage({
    receiverId,
    message,
    chatType
  }: {
    receiverId: string;
    message: string;
    chatType: string;
  }) {
    if (socket.value?.connected) {
      socket.value.emit("sendMessage", {
        receiverId: receiverId,
        message: message,
        chatType
      });
    }
  }

  return {
    socket,
    connect,
    disconnect,
    sendMessage
  };
});
